/**
 * 广寒宫
 * 网址:www.guanghangong.xyz
 */
package org.moon.framework.autoconfigure.datasource;

import com.zaxxer.hikari.HikariDataSource;
import lombok.extern.slf4j.Slf4j;
import org.moon.framework.autoconfigure.MoonConstants;
import org.moon.framework.autoconfigure.datasource.aop.DataSourceAspect;
import org.moon.framework.autoconfigure.datasource.routing.DynamicDataSource;
import org.moon.framework.autoconfigure.datasource.routing.DynamicDataSourceContextHolder;
import org.moon.framework.autoconfigure.exception.domain.MoonException;
import org.moon.framework.autoconfigure.mybatisplus.props.JdbcProperties;
import org.moon.framework.autoconfigure.tenant.props.MoonTenantProperties;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import java.util.HashMap;
import java.util.Map;

/**
 * 动态数据源
 * @author moon
 */
@Configuration
@EnableConfigurationProperties({JdbcProperties.class, MoonTenantProperties.class})
@Slf4j
public class DynamicDataSourceAutoConfiguration {

    @Bean
    @ConditionalOnProperty(value = "moon.data-source-dynamic",matchIfMissing=false)
    public DataSourceAspect dataSourceAspect(MoonTenantProperties moonTenantProperties){
        if(MoonConstants.TenantTypeEnum.datasource.name().equalsIgnoreCase(moonTenantProperties.getType())){
            throw new MoonException("数据源租户模式下，不能开启多数据源...");
        }
        log.info("开启动态数据源模式...");
        return new DataSourceAspect();
    }

    /**
     * 初始化主数据源
     * 主数据源在系统启动时读取配置文件中的连接信息完成成初始化，目的是为了方面在后期切换时没有指定目标数据源，则默认切回主数据源
     */
    @Bean("dataSource")
    @Primary
    @ConditionalOnProperty(value = "moon.data-source-dynamic",matchIfMissing=false)
    public DynamicDataSource multipleDataSource (JdbcProperties jdbcProperties,MoonTenantProperties moonTenantProperties) {
        if(MoonConstants.TenantTypeEnum.datasource.name().equalsIgnoreCase(moonTenantProperties.getType())){
            throw new MoonException("数据源租户模式下，不能开启多数据源...");
        }
        log.info("主数据源初始化完成....");
        Map< Object, Object > targetDataSources = new HashMap<>();
        HikariDataSource hikariDataSource = DynamicDataSourceContextHolder.buildDataSource(jdbcProperties);
        String dsName = "default";
        targetDataSources.put(dsName, hikariDataSource );
        DynamicDataSource dynamicMultipleDataSource = new DynamicDataSource(hikariDataSource,targetDataSources);
        return dynamicMultipleDataSource;
    }
}